<?php
// 公共助手函数

use think\exception\HttpResponseException;
use think\Response;


//api接口url
function curlRequest($type, $url, $contentType, $data = [], $timeout = 60)
{
    try {
        $type = strtoupper($type);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url); // 设置请求链接
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 不直接输出页面
        curl_setopt($curl, CURLOPT_HEADER, 0); // 获取响应头向下
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);   // 请求超时时间，单位：秒
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1');
        if (substr($url, 0, 5) == 'https') {
            // 自动判断是否是 https 提交
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            // https请求，不验证证书和 hosts
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        // 判断 Content-Type 类型
        if ($contentType == 'json') {
            curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
        }
        if ($contentType == 'form') {
            curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/x-www-form-urlencoded']);
        }
        switch ($type) {
            case "GET" :
                curl_setopt($curl, CURLOPT_HTTPGET, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                break;
            case "POST":
                curl_setopt($curl, CURLOPT_POST, true);
                if ($contentType == 'json') {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                }
                if ($contentType == 'form') {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                }
                break;
        }
        $result = curl_exec($curl);
        $err_code = curl_errno($curl);
        $curlInfo = curl_getinfo($curl);
        curl_close($curl);
        if ($err_code) {
            return ['status' => 'error', 'msg' => 'sendRequestError:' . $err_code];
        }
        if ($curlInfo['http_code'] == 200) {
            // return $result;
            return json_decode($result, true);
        }
        return false;
    } catch (\Exception $e) {
        return ['status' => 'error', 'msg' => $e->getMessage()];
    }
}
function success($msg = ' ', $date = null)
{
    return json([
        'code' => 1,
        'msg' => $msg,
        'date' => $date
    ]);
}

//统一失败返回
function error($msg = ' ', $date = null)
{
    return json([
        'code' => 0,
        'msg' => $msg,
        'date' => $date
    ]);
}

//生成随机字符串
function createRandStr($length = 8)
{
    $str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randStr = '';
    for ($i = 0; $i < $length; $i++) {
        $randStr .= $str[mt_rand(0, 35)];
    }
    return $randStr;
}

//生成token
function singToken($userId, $username)
{
    $data = [
        //签发人
        'iss' => request()->domain(),
        //签发时间
        'iat' => time(),
        //自定义数据
        'data' => [
            'user_id' => $userId,
            'username' => $username,

        ]
    ];
    $key = config('app.jwt_key');
    $token = \Firebase\JWT\JWT::encode($data, $key, 'HS256');
    return $token;
}


//检查验证码是否错误
function checkSmsCode($mobile, $code)
{
    $log = \think\facade\Db::name('code_log')
        ->where('mobile', $mobile)
        ->find();
    if (!$log) {
        return '没有账号';
    }
    if ($log['code'] != $code) {
        return '验证码错误';
    }
    if (time() - $log['send_time'] > 60) {
        Db::name('code_log')->where('mobile', $mobile)->delete();
        return '验证码超时';
    }
    Db::name('code_log')->where('mobile', $mobile)->delete();
    return true;
}
